package cn.edu.ncut.cs.springboot.petmanagementsystem.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * WebSocket控制器
 */
@Slf4j
@Controller
@RequestMapping("/ws")
@Tag(name = "WebSocket实时通知模块")
public class WebSocketController {

    private final SimpMessagingTemplate messagingTemplate;

    public WebSocketController(SimpMessagingTemplate messagingTemplate) {
        this.messagingTemplate = messagingTemplate;
    }

    /**
     * 处理客户端发送的消息
     * 客户端发送到: /app/notification/send
     */
    @MessageMapping("/notification/send")
    @SendTo("/topic/notifications")
    public Map<String, Object> handleNotification(Map<String, Object> message) {
        log.info("收到WebSocket消息: {}", message);
        
        Map<String, Object> response = new HashMap<>();
        response.put("type", "notification");
        response.put("content", message.get("content"));
        response.put("timestamp", LocalDateTime.now().toString());
        response.put("from", "system");
        
        return response;
    }

    /**
     * 发送通知给指定用户
     */
    @Operation(summary = "测试发送WebSocket通知")
    @GetMapping("/notification/test")
    @ResponseBody
    public Map<String, Object> sendTestNotification(
            @Parameter(description = "用户ID") @RequestParam(required = false) Long userId,
            @Parameter(description = "通知消息") @RequestParam(required = false) String message) {
        try {
            Map<String, Object> notification = new HashMap<>();
            notification.put("type", "test");
            notification.put("content", message != null ? message : "这是一条测试通知");
            notification.put("timestamp", LocalDateTime.now().toString());
            notification.put("userId", userId);

            // 发送给指定用户
            if (userId != null) {
                messagingTemplate.convertAndSendToUser(
                    userId.toString(),
                    "/queue/notifications",
                    notification
                );
            } else {
                // 广播给所有用户
                messagingTemplate.convertAndSend("/topic/notifications", notification);
            }

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("message", "通知发送成功");
            return result;
        } catch (Exception e) {
            log.error("发送通知失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", "发送失败: " + e.getMessage());
            return result;
        }
    }
}

